﻿using Microsoft.Extensions.Configuration;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Text;

namespace Ekton_Manage_Framework.Redis
{
    public class Connection
    {
        public static StackExchange.Redis.ConnectionMultiplexer Redis = null;
        public volatile StackExchange.Redis.IDatabase db = null;
        private readonly object redisConnectionLock = new object();

        public Connection(IConfiguration configuration)
        {
            _configuration = configuration;
            Redis = GetRedisConnection();
            this.db = Redis.GetDatabase();
        }
        private IConfiguration _configuration;

        /// <summary>
        /// 获取连接实例
        /// </summary>
        /// <returns></returns>
        private ConnectionMultiplexer GetRedisConnection()
        {
            //如果已经连接实例，直接返回
            if (Redis != null && Redis.IsConnected)
            {
                return Redis;
            }
            //加锁，防止异步编程中，出现单例无效的问题
            lock (redisConnectionLock)
            {
                if (Redis != null)
                {
                    //释放redis连接
                    Redis.Dispose();
                }
                try
                {
                    Redis = ConnectionMultiplexer.Connect($"{_configuration["RedisConnectionStrings:dbconn"]}");
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message);
                }
            }
            return Redis;
        }
    }
}
